package net.lzzy.practicesapi1.aspects;

import net.lzzy.practicesapi1.entities.User;
import net.lzzy.practicesapi1.services.UserService;
import net.lzzy.practicesapi1.utils.AspectUtil;
import net.lzzy.practicesapi1.utils.JwtUtil;
import net.lzzy.practicesapi1.web.models.ApiResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.UUID;

/**
 * @author lyz
 */
@Aspect
@Component
public class AdminAspect {
    private final UserService service;

    @Autowired
    public  AdminAspect (UserService service) {
    this.service = service;
    }
    @Pointcut("execution(* net.lzzy.practicesapi1.web.admin.UserApiController.*(..))")
    private void adminPoint(){}
@Around("adminPoint()")
    public ApiResult aroundAdminController(ProceedingJoinPoint point) throws Throwable {
        String token = AspectUtil.getToken(point);
        String userId = JwtUtil.verifyToken(token);
        if (userId == null){
            return new ApiResult(false,"认证信息已失效，请重新登录",null);
        }
    User user = service.getUser(UUID.fromString(userId));
    if (user == null){
        return new ApiResult(false,"认证信息已失效，请重新登录",null);
    }
    int[] allowRoles = new int[] {User.TYPE_ADMIN};
    if (Arrays.stream(allowRoles).noneMatch(r  ->r == user.getType())){
        return  new ApiResult(false,"没有权限，请登录为管理员",null);

    }
    return (ApiResult) point.proceed();
}
}
